// router.js - 前端路由控制
// 注意：Utils模块未使用，已移除导入

class Router {
    constructor() {
        this.routes = [];
        this.currentPath = '';
        console.log('[Router] Router instance created');
    }

    // 初始化路由
    init() {
        console.log('[Router] Router initialized');
        // 确保DOM加载完成后再处理路由
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                console.log('[Router] DOM content loaded, handling route change');
                this.handleRouteChange();
            });
        } else {
            console.log('[Router] DOM already loaded, handling route change');
            this.handleRouteChange();
        }

        // 监听路由变化
        window.addEventListener('popstate', () => {
            console.log('[Router] Popstate event triggered');
            this.handleRouteChange();
        });

        // 拦截所有链接点击
        document.addEventListener('click', (e) => {
            const target = e.target.closest('a');
            if (target && target.getAttribute('href') && !target.getAttribute('target')) {
                e.preventDefault();
                const href = target.getAttribute('href');
                console.log(`[Router] Link clicked: ${href}`);
                this.navigateTo(href);
            }
        });
    }

    // 注册路由
    registerRoute(path, callback) {
        console.log(`[Router] Route registered: ${path}`);
        this.routes.push({
            path,
            callback
        });
    }

    // 路由导航
    navigateTo(path) {
        console.log(`Navigating to: ${path}`);
        window.history.pushState(null, null, path);
        this.handleRouteChange();
    }

    // 处理路由变化
    handleRouteChange() {
        const path = window.location.pathname;
        this.currentPath = path;
        console.log(`[Router] Route changed to: ${path}`);
        console.log(`[Router] Registered routes: ${JSON.stringify(this.routes.map(r => r.path))}`);

        // 获取app容器
        const appContainer = document.getElementById('app-container');
        if (!appContainer) {
            console.error('[Router] app-container not found');
            return;
        }

        // 查找匹配的路由
    console.log(`[Router] Current path: ${path}`);
    console.log(`[Router] Registered routes count: ${this.routes.length}`);
    console.log(`[Router] Registered routes: ${JSON.stringify(this.routes.map(r => r.path))}`);

    // 首先尝试精确匹配
    let route = this.routes.find(route => route.path === path);
    if (route) {
        console.log(`[Router] Matched exact route: ${route.path}`);
        try {
            console.log(`[Router] Executing route callback for: ${route.path}`);
            route.callback(appContainer);
        } catch (error) {
            console.error(`[Router] Error executing route callback: ${error.message}`);
            console.error(`[Router] Error stack: ${error.stack}`);
            appContainer.innerHTML = `<h1>Error</h1><p>${error.message}</p>`;
        }
    } else {
        // 尝试去掉末尾的斜杠进行匹配
        const pathWithoutSlash = path.endsWith('/') ? path.slice(0, -1) : path;
        console.log(`[Router] Trying path without trailing slash: ${pathWithoutSlash}`);
        route = this.routes.find(route => route.path === pathWithoutSlash);
        if (route) {
            console.log(`[Router] Matched route without trailing slash: ${route.path}`);
            try {
                route.callback(appContainer);
            } catch (error) {
                console.error(`[Router] Error executing route callback: ${error.message}`);
                appContainer.innerHTML = `<h1>Error</h1><p>${error.message}</p>`;
            }
        } else {
            // 尝试通配符匹配
            console.log(`[Router] Trying wildcard route`);
            route = this.routes.find(route => route.path === '*');
            if (route) {
                console.log(`[Router] Matched wildcard route: ${route.path}`);
                try {
                    route.callback(appContainer);
                } catch (error) {
                    console.error(`[Router] Error executing wildcard route callback: ${error.message}`);
                    appContainer.innerHTML = `<h1>Error</h1><p>${error.message}</p>`;
                }
            } else {
                // 没有匹配的路由
                console.error(`[Router] No route matched for: ${path}`);
                this.handleNotFound(appContainer);
            }
        }
    }

        // 更新活动链接
        this.updateActiveLinks();
    }

    // 处理404
    handleNotFound(appContainer) {
        console.error('[Router] 404 Not Found');
        // 使用传入的appContainer参数，不再重新获取

        if (appContainer) {
            appContainer.innerHTML = '<h1>404 Not Found</h1><p>页面不存在</p>';
        } else {
            console.error('[Router] app-container not found when handling 404');
        }
    }

    // 更新活动链接
    updateActiveLinks() {
        const links = document.querySelectorAll('a');
        links.forEach(link => {
            const href = link.getAttribute('href');
            if (href === this.currentPath) {
                link.classList.add('active');
            } else {
                link.classList.remove('active');
            }
        });
    }

    // 重定向
    redirectTo(path) {
        console.log(`Redirecting to: ${path}`);
        window.location.href = path;
    }
}

// 注意：authService在需要时通过window.authService访问
// 创建单例实例
console.log('[Router] Creating singleton instance');
const router = new Router();
console.log('[Router] Singleton instance created');

// 暴露到全局作用域
window.router = router;